package com.dzsw.test.controller;

import com.dzsw.test.jxls.DataFour;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RestController
public class DemoController {

    @GetMapping("/test")
    public String test() {
        return "ok";
    }

    @GetMapping("/test1")
    public void test1(HttpServletResponse res) {
        String contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        res.setContentType(contentType);
        res.addHeader("content-disposition", "inline;filename=test.xlsx");
        List<DataFour> dataList = generateData4();
//        String src = "E:\\data\\desktop\\客户协议图片\\银盛配置模板\\template_4.xlsx";
        try (InputStream is = this.getClass().getResourceAsStream("/excelTemplate/template_4.xlsx")) {
            try (OutputStream os = res.getOutputStream()) {
                Context context = new Context();
                context.putVar("dataList", dataList);
                JxlsHelper.getInstance().processTemplate(is, os, context);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<DataFour> generateData4() {
        List<DataFour> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new DataFour(
                    "code_" + i,
                    "legal_name_" + i,
                    "legal_cert_no_" + i,
                    "phone_" + i,
                    "address_" + i,
                    "licence_number_" + i
            ));
        }
        return list;
    }
}
